package com.chagee.store.operation.server.service.biz;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.api.request.OrderDeviceInfoRequest;
import com.chagee.store.operation.api.request.OrderDeviceRequest;
import com.chagee.store.operation.api.request.OrderInfoRequest;
import com.chagee.store.operation.api.request.StoreInfoRequest;
import com.chagee.store.operation.api.request.StoreOrderDeviceRequest;
import com.chagee.store.operation.api.response.StoreOderDeviceResponse;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.config.StoreOrderDeviceConfig;
import com.chagee.store.operation.server.entity.StoreOrderDeviceDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.service.BasicTaskConfigurationService;
import com.chagee.store.operation.server.event.service.StoreOrderDeviceBaseService;
import com.chagee.store.operation.server.event.service.StoreTaskRelationBaseService;
import com.chagee.store.operation.server.event.service.TaskExecutionBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderReceiverBaseService;
import com.personnel.auth.service.PersonnelAuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author : hk
 * @Date : 2024/7/10
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class StoreOrderDeviceBizService {

	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;
	@Resource
	private StoreTaskRelationBaseService storeTaskRelationBaseService;
	@Resource
	private BasicTaskConfigurationService basicTaskConfigurationService;
	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;
	@Resource
	private PersonnelAuthService personnelAuthService;
	@Resource
	private StoreOrderDeviceConfig storeOrderDeviceConfig;
	@Resource
	private StoreOrderDeviceBaseService storeOrderDeviceBaseService;

	@Resource
	private WorkOrderBaseService workOrderBaseService;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	public List<StoreOderDeviceResponse> deviceConfig(StoreOrderDeviceRequest request) {
		LambdaQueryWrapper<StoreOrderDeviceDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StoreOrderDeviceDO::getWorkOrderNumber, request.getWorkOrderNumber());
		List<StoreOrderDeviceDO> list = storeOrderDeviceBaseService.list(queryWrapper);

		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(WorkOrderDO::getWorkOrderNumber, request.getWorkOrderNumber());
		List<WorkOrderDO> workOrderDOList = workOrderBaseService.list(wrapper);

		List<StoreOderDeviceResponse> result = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(list)) {
			Map<String,String> map = JSONObject.parseObject(storeOrderDeviceConfig.getOrderDevice(), Map.class);
			List<String> orderDevice = new ArrayList<>(map.keySet());

			List<String> deviceNameList = list.stream().map(StoreOrderDeviceDO::getDeviceName).collect(Collectors.toList());
			List<String> devices = new ArrayList<>();
			for (String deviceName : orderDevice) {
				if (!deviceNameList.contains(deviceName)) {
					devices.add(deviceName);
				}
			}
			//List<String> deviceList = orderDevice.stream().filter(s -> !deviceNameList.contains(s)).collect(Collectors.toList());
			//未配置的设备信息
			result = devices.stream().distinct().map(s -> {
				StoreOderDeviceResponse response = new StoreOderDeviceResponse();
				response.setDeviceName(s);
				response.setDeviceSign(map.get(s));
				return response;
			}).collect(Collectors.toList());
			//已配置的设备
			List<StoreOderDeviceResponse> OderDeviceList = list.stream().map(s -> {
				StoreOderDeviceResponse response = new StoreOderDeviceResponse();
				BeanUtils.copyProperties(s, response);
				return response;
			}).collect(Collectors.toList());
			result.addAll(OderDeviceList);
		} else {
			Map<String,String> map = JSONObject.parseObject(storeOrderDeviceConfig.getOrderDevice(), Map.class);
			List<String> orderDevice = new ArrayList<>(map.keySet());
			result = orderDevice.stream().distinct().map(s -> {
				StoreOderDeviceResponse response = new StoreOderDeviceResponse();
				response.setDeviceName(s);
				response.setDeviceSign(map.get(s));
				if (!StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType().equals(workOrderDOList.get(0).getDocumentStatus())) {
					response.setOperation(1);
				}
				return response;
			}).collect(Collectors.toList());
		}
		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	public Boolean submitDeviceConfig(OrderInfoRequest request) {
		boolean result = false;
		if (StringUtils.isNotBlank(request.getWorkOrderNumber())) {
			String workOrderNumber = request.getWorkOrderNumber();
			LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(WorkOrderDO::getWorkOrderNumber, workOrderNumber);
			List<WorkOrderDO> list = workOrderBaseService.list(queryWrapper);

			if (CollectionUtils.isNotEmpty(list)) {
				WorkOrderDO workOrderDO = list.get(0);
				//供应商直接接单越过功夫小程序提示语
				if (!StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType().equals(workOrderDO.getDocumentStatus())) {
					//供应商已接单，请返回刷新
					throw new BizException(BizErrorCode.SUBMIT_DEVICE_REPEAT);
				}
				//待交接变更为待接单
				if (StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType().equals(workOrderDO.getDocumentStatus())) {
					workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.PENDING_ORDERS.getType());
					result = workOrderBaseService.updateById(workOrderDO);
				}
			}
		}

		//回退版本
		/*boolean result = false;
		if (CollectionUtils.isNotEmpty(request.getOrderDeviceList())) {
			List<StoreOrderDeviceDO> orderDeviceDOS = request.getOrderDeviceList().stream().map(s -> {
				StoreOrderDeviceDO orderDeviceDO = new StoreOrderDeviceDO();
				BeanUtils.copyProperties(s, orderDeviceDO);
				return orderDeviceDO;
			}).collect(Collectors.toList());
			result = storeOrderDeviceBaseService.saveBatch(orderDeviceDOS);

			LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(WorkOrderDO::getWorkOrderNumber, request.getOrderDeviceList().get(0).getWorkOrderNumber());
			List<WorkOrderDO> list = workOrderBaseService.list(queryWrapper);

			if (CollectionUtils.isNotEmpty(list)) {
				WorkOrderDO workOrderDO = list.get(0);
				if (StringUtils.isNotBlank(request.getTransfer())) {
					workOrderDO.setTransfer(request.getTransfer());
				}
				//待交接变更为待接单
				if (StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType().equals(workOrderDO.getDocumentStatus())) {
					workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.PENDING_ORDERS.getType());
				}
				result =  workOrderBaseService.updateById(workOrderDO);
			}
		}*/

		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	public String saveDeviceConfig(OrderDeviceInfoRequest request) {
		boolean b = request.getOrderDeviceList().stream().anyMatch(s -> StringUtils.equals("0", s.getOperation().toString()));
		if (b && StringUtils.isBlank(request.getTransfer())) {
			throw new BizException(BizErrorCode.ORDER_DEVICE_FAIL);
		}
		Map<String, String> map = JSONObject.parseObject(storeOrderDeviceConfig.getOrderDevice(), Map.class);
		List<String> orderDevice = new ArrayList<>(map.keySet());
		if (CollectionUtils.isNotEmpty(request.getOrderDeviceList())) {
			List<StoreOrderDeviceDO> orderDeviceDOS = new ArrayList<>();
			for (OrderDeviceRequest orderDeviceRequest : request.getOrderDeviceList()) {
				StoreOrderDeviceDO orderDeviceDO = new StoreOrderDeviceDO();
				BeanUtils.copyProperties(orderDeviceRequest, orderDeviceDO);
				if (StringUtils.isNotBlank(orderDeviceRequest.getId())) {
					orderDeviceDO.setId(Long.parseLong(orderDeviceRequest.getId()));
				}
				orderDeviceDOS.add(orderDeviceDO);
			}
			List<StoreOrderDeviceDO> collect = new ArrayList<>();
			List<StoreOrderDeviceDO> deviceDOS = new ArrayList<>();
			//通过有无id 来判断修改或新增
			for (StoreOrderDeviceDO orderDeviceDO : orderDeviceDOS) {
				if (ObjectUtils.isNotEmpty(orderDeviceDO.getId())) {
					collect.add(orderDeviceDO);
				}
				if (ObjectUtils.isEmpty(orderDeviceDO.getId())) {
					deviceDOS.add(orderDeviceDO);
				}
			}
			if (CollectionUtils.isNotEmpty(deviceDOS)) {
				storeOrderDeviceBaseService.saveBatch(deviceDOS);
			}
			if (CollectionUtils.isNotEmpty(collect)) {
				storeOrderDeviceBaseService.updateBatchById(collect);
			}

			if (StringUtils.isNotBlank(request.getTransfer())) {
				String workOrderNumber = request.getOrderDeviceList().get(0).getWorkOrderNumber();
				LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(WorkOrderDO::getWorkOrderNumber, workOrderNumber);
				List<WorkOrderDO> list = workOrderBaseService.list(queryWrapper);
				if (CollectionUtils.isNotEmpty(list)) {
					WorkOrderDO workOrderDO = list.get(0);
					workOrderDO.setTransfer(request.getTransfer());
					workOrderBaseService.updateById(workOrderDO);
				}
			}
		}

		//判断是否已经保存全部设备信息
		String workOrderNumber = request.getOrderDeviceList().get(0).getWorkOrderNumber();
		LambdaQueryWrapper<StoreOrderDeviceDO> storeOrderDeviceWrapper = new LambdaQueryWrapper<>();
		storeOrderDeviceWrapper.eq(StoreOrderDeviceDO::getWorkOrderNumber, workOrderNumber);
		List<StoreOrderDeviceDO> list = storeOrderDeviceBaseService.list(storeOrderDeviceWrapper);
		if (CollectionUtils.isNotEmpty(list)) {
			if (orderDevice.size() == list.size()) {
				return "isAll";
			}
		}
		return null;
	}

	// 沿用上次配置信息
	public List<StoreOderDeviceResponse> recentlyConfig(StoreInfoRequest request) {
		List<StoreOderDeviceResponse> result = new ArrayList<>();
		List<StoreOrderDeviceDO> list = storeOrderDeviceBaseService.getBaseMapper().queryRecentlyList(request);

		if (CollectionUtils.isNotEmpty(list)) {
			result = list.stream().map(s -> {
				StoreOderDeviceResponse response = new StoreOderDeviceResponse();
				BeanUtils.copyProperties(s, response);
				response.setId(null);
				return response;
			}).collect(Collectors.toList());
		}
		return result;
	}

}
